let Boat = require('./../../model/boat')
let mongoose = require('mongoose')

let create = async function(ctx, next) {
    let body = ctx.request.body;
    let auth = ctx.auth;
    // 建议新建者id等信息
    let createrId = auth._id
    let createrMobile = auth.mobile
    let verify = new global.sess.VerifyField([{
        name: 'boatName',
        msg: '队伍名称必填'
    },{
        name: 'bostAddress',
        msg: '队伍地址必填'
    },{
        name: 'boatPhone',
        msg: '队伍联系电话必填'
    }]);
    verify.getField(ctx, next);
    Boat.create({
        boatName: body.boatName,
        bostAddress: body.bostAddress,
        boatPhone: body.boatPhone,
        boatRemarks: body.boatRemarks,
        boatPrincipal: body.boatPrincipal,
        boatMobile: body.boatMobile,
        createrId,
        createrMobile
    });
    ctx.body = new resModel.Success('添加成功')
    
}

let update = async function(ctx, next) {
    let body =  ctx.request.body;
    let auth = ctx.auth;
    if (!body._id) {
        ctx.body = new resModel.def('队伍ID必填')
    } else {
        await Boat.findOneAndUpdate({_id: mongoose.Types.ObjectId(body._id)}, {
            $set: Obect.assign(body, { updateId: auth._id, updateMobile: auth.mobile})
        }, { new: true }).then(res=> {
            if (res) {
                ctx.body = new resModel.Success('修改成功')
            } else {
                ctx.body = new resModel.Delete()
            }
        }).catch(error=> {
            ctx.body = new resModel.Server()
        })
    }
}

let remove = async function(ctx, next) {
    let body =  ctx.request.body;
    if (!body._id) {
        ctx.body = new resModel.def('队伍ID必填')
    } else {
        await Boat.findByIdAndRemove(mongoose.Types.ObjectId(body._id)).then(res => {
            if (res) {
                ctx.body = new resModel.Success('修改成功')
            } else {
                ctx.body = new resModel.Delete()
            }
        }).catch(error => {
            ctx.body = new resModel.Server()
        })
    }
}

let list = async function(ctx, next) {
    // 建议新建者id等信息
    let auth = ctx.auth;
    let createrId = auth._id;
    let createrMobile = auth.mobile;
    let cb = await Boat.find({createrId});
    if (!cb) {
        sess.mongoError(ctx, next, error)
    } else {
        ctx.body = new resModel.Success(cb, '查询成功')
    }
}

module.exports = {
    create,
    update,
    remove,
    list
}